import type { Bean, PageBean, ResultBean, ValueEnum } from '../../interface';
import { typeUtil } from '../boolean';
import type { ColProps } from 'antd/lib/col';

// export * from './transToJsx';

export const getTextFromEnum = (value: string, optionEnum: Bean) => {
  let text = '未知类型';
  // eslint-disable-next-line no-restricted-syntax
  for (const item in optionEnum) {
    if (`${optionEnum[item]}` === `${value}`) {
      text = item;
      break;
    }
  }
  return text;
};

export function enumToLabelValue(enumObj: Bean, isReverseLabelValue = false) {
  const list: Bean[] = [];
  const keys = Object.keys(enumObj || {});
  keys.forEach((item) => {
    const obj: Bean = {};
    if (!isReverseLabelValue) {
      obj.label = item;
      obj.value = enumObj[item];
    } else {
      obj.value = item;
      obj.label = enumObj[item];
    }
    list.push(obj);
  });

  return list;
}

export function transToValueEnum(enumObj: Bean, includeState = false): ValueEnum {
  const keys = Object.keys(enumObj || {});
  const obj: ValueEnum = {};
  keys.forEach((key) => {
    if (includeState) {
      obj[enumObj[key]] = {
        text: key,
        status: 'Default',
      };
    } else {
      obj[enumObj[key]] = {
        text: key,
      };
    }
  });
  console.log('transToValueEnum obj', obj);
  return obj;
}

export const setTimeoutAsync = (timer: number) => {
  return new Promise<void>((resolve) => {
    setTimeout(() => {
      resolve();
    }, timer);
  });
};

/**
 * 根据传入的数，加千分位与保留小数点后n位；
 * @param {*} value 要格式化的数据
 * @param {*} pointCount 保留小数点的位数
 */
export function toDecimalNumber(value: number = 0, pointCount: number = 2): string {
  const withPoint = (+value).toFixed(pointCount);
  const reg = /(\d{1,3})(?=(\d{3})+(\.|$))/g;
  return withPoint.replace(reg, '$1,');
}

export function removeEmptyFields(obj: Bean): Bean {
  const keys = Object.keys(obj);
  const newObj: Bean = {};
  keys.forEach((key) => {
    const value = obj[key];
    const isRemove = typeUtil.isEmpty(value);
    if (!isRemove) {
      newObj[`${key}`] = value;
    }
  });

  return newObj;
}

export function getDefaultFormLayout() {
  const rowLayout: Record<string, ColProps> = {
    labelCol: { span: 8 },
    wrapperCol: { span: 14 },
  };
  return rowLayout;
}

export function calcPageBean(result: PageBean | Bean): PageBean {
  const { pageSize = 10, current = 1, total = 0, totalPageSize = 0 } = result;
  return {
    pageSize,
    current,
    total,
    totalPageSize,
  };
}

export function commFilterOption(inputValue: string, option: Bean) {
  return option.props.children.toUpperCase().indexOf(inputValue.toUpperCase()) !== -1;
}

export function genResultBeanData<T = Bean>(success: boolean): ResultBean<T> {
  const message = success ? 'OK' : 'FAIL';
  const result = {
    success,
    code: success ? 200 : 500,
    message,
  };
  return result as ResultBean<T>;
}
